<?php
/**
 * Created by PhpStorm.
 * Script Name: Bot.php
 * Create: 2023/2/14 10:34
 * Description:
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\crontab\controller;

use app\common\service\Queue;
use app\PluginController;
use plugin\wechat\app\model\BotTask;
use plugin\wechat\app\model\BotMoments as MomentsM;
use plugin\wechat\app\model\BotMomentsFollow as MomentsFollowM;
use plugin\wechat\app\service\BotTask as TaskService;
use plugin\wechat\app\service\BotSetting as SettingService;
use plugin\wechat\app\service\BotMoments as MomentsService;

class Bot extends PluginController
{

    /**
     * @var BotTask
     */
    private BotTask $taskM;
    /**
     * @var MomentsM
     */
    private MomentsM $momentsM;
    /**
     * @var MomentsFollowM
     */
    private MomentsFollowM $momentsFollowM;

    public function __construct()
    {
        parent::__construct();
        $this->taskM = new BotTask();
        $this->momentsM = new MomentsM();
        $this->momentsFollowM = new MomentsFollowM();
    }

    /**
     * 跟圈
     * @return bool
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function followMoments(){
        if(! count($list = $this->momentsFollowM->where('status', 1)
            ->select())){
            return true;
        }

        $delay = 0;
        foreach ($list as $item){
            //放入任务队列
            Queue::push([
                'consumer' => ['\\plugin\\wechat\\app\\queue\\Bot', 'followMoments'],
                'task' => $item,
            ]);
            $delay += 1;
        }
        //echo count($list);
    }

    /**
     * 发送朋友圈
     * @throws \Psr\SimpleCache\InvalidArgumentException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function sendMoments(){
        if(count($list = $this->momentsM->where('status', 1)
            ->whereNotNull('media_id')
            ->where("plan_time", "<=", time())
            ->where("publish_time", "=", 0)
            ->select())){
            foreach ($list as $item){
                MomentsService::publishMoments($item);
            }
        }
        //echo count($list);
    }

    /**
     * 群发任务
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function runTask(){
        $view_table = $this->taskM->where('status', 1)
            ->whereNotNull('wxids')
            ->whereNotNull('medias')
            ->where("(complete_time=0 and circle=".TaskService::CIRCLE_SINGLE." and plan_time <= ".time().") or (circle=" . TaskService::CIRCLE_DAILY .
                " and plan_hour<='".date('H:i:s')."' and complete_time<".strtotime(date('Ymd 00:00')).")")
            ->field('id')
            ->buildSql();

        $task_list = $this->taskM->alias('bt')
            ->join('wechat_bot bot', 'bot.id=bt.bot_id')
            ->join($view_table . ' t1', 't1.id=bt.id')
            ->where('bot.alive' ,'=', 1)
            ->field(['bot.uuid', 'bot.uin', 'bot.app_key', 'bot.company_id','bot.url', 'bot.protocol','bt.wxids', 'bt.medias', 'bt.id','bt.circle','bt.complete_time','bt.atall'])
            ->select();

        if(count($task_list)){
            foreach($task_list as $task){
                $rKey = wechat_cache_key("bottask" . $task['id']);
                if(cache($rKey)){
                    continue;
                }

                if(!empty($task['wxids']) && !empty($task['medias'])){
                    $this->taskM->update(['id' => $task['id'], 'complete_time' => time()]);

                    $medias = json_decode($task['medias'], true);
                    foreach ($medias as $media){
                        $task['media_type'] = $media['type'];
                        $task['media_id'] = $media['id'];
                        $extra = ['atall' => $task['atall']];
                        $wxids = explode(',', $task['wxids']);
                        $delay = 0;
                        foreach ($wxids as $to_wxid){
                            //批量发送消息
                            Queue::push([
                                'consumer' => ['\\plugin\\wechat\\app\\queue\\Bot', 'sendMsgBatch'],
                                'task' => $task,
                                'reply' => $task,
                                'to_wxid' => $to_wxid,
                                'extra' => $extra,
                                'delay' => $delay
                            ]);
                            $delay += SettingService::getStepTime($task['company_id']);
                        }
                    }
                }
                cache($rKey, null);
            }
            //echo (count($task_list) . ' tasks run');
        }else{
            //echo (0);
        }
    }
}